package cn.com.xj.plat.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service("aliOssService")
public class AliOssService {
	final Logger logger = LoggerFactory.getLogger(getClass());

	@Value("${alioss_oss_endpoint:}")
	private String oss_endpoint;

	@Value("${alioss_access_id:}")
	private String oss_accessId;

	@Value("${alioss_access_key:}")
	private String oss_accessKey;

	@Value("${alioss_oss_bucket_name:}")
	private String oss_bucketName;

	@Value("${alioss_oss_binddomain:}")
	private String oss_bindDomain; // 默认绑定的域名

	@Value("${alioss_oss_relpathpre:}")
	private String oss_relpathpre; // 前置目录

	private static SimpleDateFormat modulePathDf = new SimpleDateFormat("yyyyMMddHHmmss");

	private OSSClient ossClient;

	public String uploadFileToOss(InputStream inputStream, String fileName,String fileType) {
		if (logger.isDebugEnabled()) {
			logger.debug("传入的文件名:" + fileName);
		}
		Date currTime = new Date(); // 当前时间
		// 判断并初始化模块路径
		String relatPath = oss_relpathpre + "/" + modulePathDf.format(currTime) + "/" + currTime.getTime() + "_"
				+ fileName + "." + fileType;
		String bindUrl = oss_bindDomain + "/" + relatPath;
		// 上传文件
		PutObjectResult pubObjectResult = this.getOssClient().putObject(oss_bucketName, relatPath, inputStream);
		logger.debug("上传结果标签值:" + pubObjectResult.getETag());
		return bindUrl;
	}

	/**
	 * 获取或创建oss客户端
	 * 
	 * @return
	 */
	private OSSClient getOssClient() {
		if (ossClient != null) {
			return ossClient;
		} else {
			ossClient = new OSSClient(oss_endpoint, oss_accessId, oss_accessKey);
			return ossClient;
		}
	}

}
